﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Threading;
using PersonaLibrary.Commands.CommandsForTotalItems;
using PersonaLibrary.Data;
using PersonaLibrary.Search;
using PersonaLibrary.View.Host;

namespace PersonaLibrary.ViewModel.MainWindowViewModel
{
	internal class MainWindowViewModel : WindowViewModel
	{
		private IViewModel _selectedViewModel;

		public MainWindowViewModel()
		{
			if (CurrentApplication != null && CurrentApplication.ViewModelCollection != null)
				CurrentApplication.ViewModelCollection.CollectionChanged += ViewModelCollectionCollectionChanged;
		}

		private void ViewModelCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
				case NotifyCollectionChangedAction.Add:
					SelectedViewModel = (IViewModel) e.NewItems[0];
					break;

				case NotifyCollectionChangedAction.Remove:
					if (ViewModelCollection.Count > 0)
					{
						if (e.OldStartingIndex >= ViewModelCollection.IndexOf(SelectedViewModel))
						{
							if (ViewModelCollection.Count > e.OldStartingIndex)
								SelectedViewModel = ViewModelCollection[e.OldStartingIndex];
							else
								SelectedViewModel = ViewModelCollection[e.OldStartingIndex - 1];
						}
					}
					else
						SelectedViewModel = null;
					break;
			}
		}

		public ObservableCollection<IViewModel> ViewModelCollection
		{
			get { return CurrentApplication.ViewModelCollection; }
		}

		public IViewModel SelectedViewModel
		{
			get { return _selectedViewModel; }
			set 
			{ 
				_selectedViewModel = value; 
				RisePropertyChanged("SelectedViewModel"); 
			}
		}
	}
}
